
#import "AliIOT_loginFlow.h"

#import "JMNetworkUtils.h"

#import <CommonCrypto/CommonDigest.h>

#import "JMIotUtils.h"
#import <ALBBOpenAccountCloud/ALBBOpenAccountSDK.h>
#import <IMSAccount/IMSAccountService.h>

@interface AliIOT_loginFlow ()<SSODelegate> {
    void (^loginSuccessBlock)(id responseObject, bool isSuccess, NSError *error);
    NSMutableDictionary *mdic_info;
}
@end

@implementation AliIOT_loginFlow

+ (NSString *)MD5ForUpper32Bate:(NSString *)str {
    if ([str length] == 0)
        return nil;

    //要进行UTF8的转码
    const char *input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }

    return digest;
}

+ (AliIOT_loginFlow *)sharedInstance {
    static AliIOT_loginFlow *Instance;
    @synchronized(Instance) {
        if (!Instance) {
            Instance = [[AliIOT_loginFlow alloc] init];
        }
    }
    return Instance;
}

- (void)dealloc {
}

- (id)init {
    self = [super init];
    if (self) {
        mdic_info = [[NSMutableDictionary alloc] init];
    }
    return self;
}

#pragma mark - 账户登录

- (void)connectWithName:(NSString *)loginName withPass:(NSString *)password
             completion:(void (^)(id _Nonnull responseObject, bool isSuccess))completion
            failedError:(void (^)(NSError *_Nonnull error))failedError {
    NSDictionary *Body = @{@"loginName" : loginName, @"password" : password};
    NSDictionary *dic = @{@"Body" : Body};

    [[JMNetworkUtils sharedInstance] connectWithUrl:@"https://myiot.jomoo.com.cn/appbackends/login"
        parameters:dic
        showHud:false
        showErrHud:false
        success:^(id _Nonnull responseObject, bool isSuccess) {
          if (completion) {
              completion(responseObject, isSuccess);
          }
        }
        failure:^(NSError *_Nonnull error) {
          if (failedError) {
              failedError(error);
          }
        }];
}

- (void)connectWithMobile:(NSString *)mobile withCode:(NSString *)code
               completion:(void (^)(id _Nonnull responseObject, bool isSuccess))completion
              failedError:(void (^)(NSError *_Nonnull error))failedError {
    NSDictionary *Body = @{@"mobile" : mobile, @"code" : code};
    NSDictionary *dic = @{@"Body" : Body};

    [[JMNetworkUtils sharedInstance] connectWithUrl:@"https://myiot.jomoo.com.cn/appbackends/phoneLogin"
        parameters:dic
        showHud:false
        showErrHud:false
        success:^(id _Nonnull responseObject, bool isSuccess) {
          if (completion) {
              completion(responseObject, isSuccess);
          }
        }
        failure:^(NSError *_Nonnull error) {
          if (failedError) {
              failedError(error);
          }
        }];
}

- (void)loginWithName:(NSString *)loginName
             withPass:(NSString *)password
           completion:(void (^)(id responseObject, bool isSuccess, NSError *error))completion {
    if ([self isOpenAccountLogin]) {
        [self openAccountLogout];
        [JMIotUtils logOut];
    }

    password = [AliIOT_loginFlow MD5ForUpper32Bate:password].lowercaseString;

    __weak __typeof(self) weakSelf = self;

    [self connectWithName:loginName
        withPass:password
        completion:^(id _Nonnull responseObject, bool isSuccess) {
          if (isSuccess) {
              if (completion) {
                  __strong __typeof(weakSelf) strongSelf = weakSelf;
                  [strongSelf->mdic_info setDictionary:responseObject];
                  strongSelf->loginSuccessBlock = nil;
                  strongSelf->loginSuccessBlock = [completion copy];
              }
              [self oauthWithAuthCode:responseObject[@"code"]];
          } else {
              NSLog(@"responseObject = %@", responseObject);
              if (completion) {
                  completion(responseObject, false, nil);
              }
          }
        }
        failedError:^(NSError *_Nonnull error) {
          NSLog(@"error = %@", error);
          if (completion) {
              completion(nil, false, error);
          }
        }];
}

- (void)loginWithMobile:(NSString *)mobile
               withCode:(NSString *)code
             completion:(void (^)(id responseObject, bool isSuccess, NSError *error))completion {
    if ([self isOpenAccountLogin]) {
        [self openAccountLogout];
        [JMIotUtils logOut];
    }

    __weak __typeof(self) weakSelf = self;

    [self connectWithMobile:mobile
        withCode:code
        completion:^(id _Nonnull responseObject, bool isSuccess) {
          if (isSuccess) {
              if (completion) {
                  __strong __typeof(weakSelf) strongSelf = weakSelf;
                  [strongSelf->mdic_info setDictionary:responseObject];
                  strongSelf->loginSuccessBlock = nil;
                  strongSelf->loginSuccessBlock = [completion copy];
              }
              [self oauthWithAuthCode:responseObject[@"code"]];
          } else {
              NSLog(@"responseObject = %@", responseObject);
              if (completion) {
                  completion(responseObject, false, nil);
              }
          }
        }
        failedError:^(NSError *_Nonnull error) {
          NSLog(@"error = %@", error);
          if (completion) {
              completion(nil, false, error);
          }
        }];
}

- (BOOL)isOpenAccountLogin {
    return [[ALBBOpenAccountSession sharedInstance] isLogin];
}

- (void)openAccountLogout {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"IMSNotificationAccountLogout" object:nil];
    return [[ALBBOpenAccountSession sharedInstance] logout];
}

- (void)oauthWithAuthCode:(NSString *)authCode {
    id<ALBBOpenAccountSSOService> ssoService = ALBBService(ALBBOpenAccountSSOService);
    [ssoService oauthWithThirdParty:authCode delegate:self];
}

#pragma mark - SSODelegate

- (void)openAccountOAuthError:(NSError *)error Session:(ALBBOpenAccountSession *)session {
    if (!error) {
        //登录成功，发送登录成功通知，身份认证 SDK 会监听该通知进行用户身份凭证创建和管理
        NSString *loginNotificationName = [[IMSAccountService sharedService].sessionProvider accountDidLoginSuccessNotificationName];
        [[NSNotificationCenter defaultCenter] postNotificationName:loginNotificationName object:nil];
        NSLog(@"登录成功： %@", loginNotificationName);
        if (loginSuccessBlock) {
            loginSuccessBlock(mdic_info, true, nil);
        }
    } else {
        //处理登录失败
        NSString *message = [NSString stringWithFormat:@"%ld\n%@", error.code, error.localizedDescription];
        NSLog(@"message = %@", message);
        if (loginSuccessBlock) {
            loginSuccessBlock(nil, false, error);
        }
    }
}

@end
